<template>
  <div class='container'>
    <el-dialog
      :title="titleInfo"
      :visible="dialogVisible"
      width="30%"
      @close="closeDialog">
      <el-form ref="form" label-width="80px" :model="form" :rules="rules">
        <el-form-item label="所属学科" prop="subjectID" v-if="!$route.query.id">
          <el-select v-model="form.subjectID" placeholder="请选择" style="width: 100%;" >
            <el-option
              v-for="item in subjectID"
              :key="item.value"
              :label="item.label"
              :value="item.value">
              </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="标签名称" prop="tagName" >
          <el-input  placeholder="请输入目录名称" v-model="form.tagName" style="width: 100%;"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="addTags">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { add, update } from '@/api/hmmm/tags'
export default {
  name: 'addDialog',
  props: {
    dialogVisible: {
      type: Boolean,
      default: true
    },
    showTagsAdd: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      form: {
        id: null,
        tagName: null,
        subjectID: null
      },
      subjectID: [],
      rules: {
        tagName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ],
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'blur' }
        ]
      }
    }
  },
  async created () {
    const { data } = await simple()
    this.subjectID = data
  },
  computed: {
    titleInfo () {
      return this.form.id ? '编辑目录' : '新增目录'
    }
  },
  methods: {
    openTags () {
      this.dialogVisible = true
      if (this.form.id) {
        const { id, subjectID, tagName } = this.form
        this.form = { id, subjectID, tagName }
      } else {
        this.form = {
          id: null,
          subjectID: +this.$route.query.id || null,
          tagName: null
        }
      }
      // 清除校验效果
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },

    closeDialog () {
      this.$emit('closeDialog')
    },
    addTags () {
      this.$refs.form.validate(async () => {
        // if (!boo) return null
        if (!this.form.id) {
          // 发送添加请求
          await add(this.form)
        } else {
          // 修改
          await update(this.form)
        }
        this.closeDialog()
      })
    }
  }
}
</script>

<style scoped lang='less'></style>
